package com.example.mysqlsearchdemo.controllers;

import com.example.core.libs.JSONResult;
import com.example.mysqlsearchdemo.entities.Prize;
import com.example.mysqlsearchdemo.entities.User;
import com.example.mysqlsearchdemo.repositories.PrizeRepository;
import com.example.mysqlsearchdemo.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class PrizeController {

    @Autowired
    PrizeRepository prizeRepository;
    @Autowired
    UserRepository userRepository;

    @RequestMapping("/prize/list")
    public JSONResult list(@PageableDefault Pageable pageable) {
        long startTime = System.currentTimeMillis();

        Page<Prize> page = prizeRepository.findAllIsMy(pageable);

        long endTime = System.currentTimeMillis(); //获取结束时间

        return new JSONResult(page, pageable.getPageNumber()).put("执行时间：", (endTime - startTime) + "ms");
    }

    @RequestMapping("/prize/list2")
    public JSONResult list2(@PageableDefault Pageable pageable) {
        long startTime = System.currentTimeMillis();

        Page<Prize> page = prizeRepository.findAll(pageable);
        List<User> users = userRepository.findAll();
        Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, o -> o));
        page.forEach(o -> o.setUser(userMap.get(o.getUserId())));

        long endTime = System.currentTimeMillis(); //获取结束时间

        return new JSONResult(page, pageable.getPageNumber()).put("执行时间：", (endTime - startTime) + "ms");
    }

    @RequestMapping("/prize/list3")
    public JSONResult list3(@PageableDefault Pageable pageable) {
        long startTime = System.currentTimeMillis();

        Page<Prize> page = prizeRepository.findAll(pageable);
        List<Long> userIds = page.getContent().stream().map(Prize::getUserId).collect(Collectors.toList());
        List<User> users = userRepository.findByIdIn(userIds);
        Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, o -> o));
        page.forEach(o -> o.setUser(userMap.get(o.getUserId())));

        long endTime = System.currentTimeMillis(); //获取结束时间

        return new JSONResult(page, pageable.getPageNumber()).put("执行时间：", (endTime - startTime) + "ms");
    }
}
